package com.sys.dao;

import com.sys.data.code;
import com.sys.data.sqlMap;
import com.sys.handle.OnDataHandler;
import com.sys.util.console;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.*;

public class sysDao extends ConnectSQL {

  /**
   * -------------------------------------------------------------public----------------------------------------------------------------------------------
   */

  public void login(String username, String password, String userType, OnDataHandler handler) {
    JSONObject resultJson;
    String sql = "SELECT * FROM User_Table WHERE username = ? AND password = ? And userType = ?";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, username, 12);
    sqlM.put(2, password, 12);
    sqlM.put(3, userType, 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), code.ErrorAccountOrPassword);
    handler.onData(resultJson);
  }

  public void register(String username, String password, String nickName, String departmentId, String userType, String address, String sex, String age, String userDuties, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    if (!checkAccountRepetition(username)) {
      console.err("账号重复!");
      resultJson.put("code", code.ErrorAccountRepetition.value());
      resultJson.put("msg", code.ErrorAccountRepetition.msg());
      handler.onData(resultJson);
      return;
    }
    String sql = "INSERT INTO User_Table(userId,username,password,nickName,createTime,departmentId,userType,address,sex,age,userCode,userDuties) VALUES (?,?,?,?,now(),?,?,?,?,?,?,?)";
    sqlMap sqlM = new sqlMap();
    String uid = UUID.randomUUID().toString();
    console.log("存用户: [uid:" + uid + "  username:" + username + "  password:" + password + "]");
    sqlM.put(1, uid, 12);
    sqlM.put(2, username, 12);
    sqlM.put(3, password, 12);
    sqlM.put(4, nickName, 12);
    sqlM.put(5, departmentId, 12);
    sqlM.put(6, userType, 12);
    sqlM.put(7, address, 12);
    int randomCount = (int) (10000 + Math.random() * 99999);
    String userCode = new Date().getTime() + String.valueOf(randomCount);
    sqlM.put(8, sex, 12);
    sqlM.put(9, age, 12);
    sqlM.put(10, userCode, 12);
    sqlM.put(11, userDuties, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void addSupplier(String supplierName, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    if (!checkSupplierNameRepetition(supplierName)) {
      console.err("供应商名重复!");
      resultJson.put("code", code.ErrorSupplierRepetition.value());
      resultJson.put("msg", code.ErrorSupplierRepetition.msg());
      handler.onData(resultJson);
      return;
    }

    String sql = "INSERT INTO Supplier_Table(supplierId,supplierCode,supplierName,supplierCount,supplierRep,createTime) VALUES (?,?,?,?,?,now())";
    sqlMap sqlM = new sqlMap();
    String uid = UUID.randomUUID().toString();
    sqlM.put(1, uid, 12);
    int randomCount = (int) (10000 + Math.random() * 99999);
    console.log("--------------");
    String supplierCode = new Date().getTime() + String.valueOf(randomCount);
    sqlM.put(2, supplierCode, 12);
    sqlM.put(3, supplierName, 12);
    sqlM.put(4, 0, 4);
    sqlM.put(5, 1, 4);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void modifySupplier(String supplierId, int supplierRep, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    String sql = "UPDATE Supplier_Table SET supplierRep = ? WHERE supplierId = ? AND isDelete = 0";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, supplierRep, 4);
    sqlM.put(2, supplierId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void getSupplier(OnDataHandler handler) {
    JSONObject resultJson;
    String sql = "SELECT * FROM Supplier_Table WHERE isDelete = 0";
    sqlMap sqlM = new sqlMap();
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "supplierList", code.GetSupplierNULL);
    handler.onData(resultJson);
  }

  public void deleteSupplier(String supplierId, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    String sql = "UPDATE Supplier_Table SET isDelete = ? WHERE supplierId = ?";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, 1, 4);
    sqlM.put(2, supplierId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  private void reInsertJson(OnDataHandler handler, JSONObject resultJson, String sql, sqlMap sqlM) {
    int returnCode = executeUpdate(sql, sqlM);
    if (returnCode == 1) {
      resultJson.put("code", code.OK.value());
      resultJson.put("msg", code.OK.msg());
    } else {
      if (sql.toUpperCase().contains("UPDATE".toUpperCase())) {
        resultJson.put("code", code.ErrorUpdate.value());
        resultJson.put("msg", code.ErrorUpdate.msg());
      } else {
        resultJson.put("code", code.ErrorInsert.value());
        resultJson.put("msg", code.ErrorInsert.msg());
      }
    }
    if (handler != null) {
      handler.onData(resultJson);
    }
  }

  public void addDepartment(String departmentName, String departmentPrincipalId, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    if (checkDepartmentNameRepetition(departmentName)) {
      console.err("部门名称重复!");
      resultJson.put("code", code.ErrorDepartmentNameRepetition.value());
      resultJson.put("msg", code.ErrorDepartmentNameRepetition.msg());
      handler.onData(resultJson);
      return;
    }
    String sql = "INSERT INTO Department_Table(departmentId,departmentName,departmentPrincipalId,createTime) VALUES (?,?,?,now())";
    sqlMap sqlM = new sqlMap();
    String departmentId = UUID.randomUUID().toString();
    sqlM.put(1, departmentId, 12);
    sqlM.put(2, departmentName, 12);
    sqlM.put(3, departmentPrincipalId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void addWarehouse(String userId, String warehouseName, String warehouseType, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    if (!checkWarehouseNameRepetition(warehouseName)) {
      console.err("仓库名重复!");
      resultJson.put("code", code.ErrorWarehouseRepetition.value());
      resultJson.put("msg", code.ErrorWarehouseRepetition.msg());
      handler.onData(resultJson);
      return;
    }
    String sql = "INSERT INTO Warehouse_Table(warehouseId,warehouseCode,warehouseName,warehouseType,createTime,warehouseUserId) VALUES (?,?,?,?,now(),?)";
    sqlMap sqlM = new sqlMap();
    String uid = UUID.randomUUID().toString();
    int randomCount = (int) (10000 + Math.random() * 99999);
    String warehouseCode = new Date().getTime() + String.valueOf(randomCount);
    sqlM.put(1, uid, 12);
    sqlM.put(2, warehouseCode, 12);
    sqlM.put(3, warehouseName, 12);
    sqlM.put(4, warehouseType, 12);
    sqlM.put(5, userId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void getWarehouse(int warehouseType, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    if (warehouseType > 9998) {
      sql = "SELECT * FROM Warehouse_Table WHERE isDelete = 0";
    } else {
      sql = "SELECT * FROM Warehouse_Table WHERE isDelete = 0 AND warehouseType = ?";
      sqlM.put(1, warehouseType, 4);
    }
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "warehouseList", code.GetWarehouseNULL);
    if (resultJson.getInt("code") != 200) {
      handler.onData(resultJson);
      return;
    }
    JSONArray warehouseList = resultJson.getJSONArray("warehouseList");
    JSONArray arr = new JSONArray();
    for (Object obj : warehouseList) {
      JSONObject warehouseJson = JSONObject.fromObject(obj);
      if (!warehouseJson.containsKey("warehouseUserId")) {
        arr.add(warehouseJson);
        continue;
      }
      JSONObject userJson = getSqlInfo("User_Table", "userId", warehouseJson.getString("warehouseUserId"), 12);
      if (userJson.getInt("code") == 200) {
        warehouseJson.remove("warehouseUserId");
        warehouseJson.put("warehouseUserName", userJson.getString("nickName"));
      }
      arr.add(warehouseJson);
    }
    resultJson.put("warehouseList", arr);
    handler.onData(resultJson);
  }

  public void deleteWarehouse(String warehouseId, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    sqlMap sqlM = new sqlMap();
    String sql = "UPDATE Warehouse_Table SET isDelete = ? WHERE warehouseId = ?";
    sqlM.put(1, 1, 4);
    sqlM.put(2, warehouseId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void getUser(int userType, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    if (userType > 9998) {
      sql = "SELECT * FROM User_Table";
    } else {
      sql = "SELECT * FROM User_Table WHERE userType = ?";
    }
    sqlMap sqlM = new sqlMap();
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "userList", code.GetUserNULL);
    handler.onData(resultJson);
  }

  public void getUserInfo(String userId, OnDataHandler handler) {
    JSONObject resultJson;
    String sql = "SELECT * FROM User_Table WHERE userId = ?";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, userId, 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), code.ErrorUserNotFound);
    handler.onData(resultJson);
  }

  public void modifyUser(String userId, String address, String sex, int age, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    String sql = "UPDATE User_Table SET sex = ?,age = ?,address = ? WHERE userId = ?";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, sex, 12);
    sqlM.put(2, age, 4);
    sqlM.put(3, address, 12);
    sqlM.put(4, userId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void modifyUserPassword(String userId, String oldPassword, String newPassword, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    if (!checkUserOldPassword(userId, oldPassword)) {
      console.err("旧密码填写错误!");
      resultJson.put("code", code.ErrorOldPassword.value());
      resultJson.put("msg", code.ErrorOldPassword.msg());
      handler.onData(resultJson);
      return;
    }
    String sql = "UPDATE User_Table SET password = ? WHERE userId = ?";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, newPassword, 12);
    sqlM.put(2, userId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void modifyDepartment(String departmentId, String departmentPrincipalId, String departmentName, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    JSONObject departmentJson = getSqlInfo("Department_Table", "departmentId", departmentId, 12);
    if (departmentJson.getInt("code") != 200) {
      console.err("未查询到修改部门");
      resultJson.put("code", code.ErrorParam.value());
      resultJson.put("msg", code.ErrorParam.msg());
      handler.onData(resultJson);
      return;
    }

    if (!departmentJson.getString("departmentName").equals(departmentName)) {
      if (checkDepartmentNameRepetition(departmentName)) {
        console.err("部门名称重复!");
        resultJson.put("code", code.ErrorDepartmentNameRepetition.value());
        resultJson.put("msg", code.ErrorDepartmentNameRepetition.msg());
        handler.onData(resultJson);
        return;
      }
    }

    String sql = "UPDATE Department_Table SET departmentPrincipalId = ?,departmentName = ? WHERE departmentId = ? AND isDelete = 0";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, departmentPrincipalId, 12);
    sqlM.put(2, departmentName, 12);
    sqlM.put(3, departmentId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void deleteDepartment(String departmentId, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    String sql = "UPDATE Department_Table SET isDelete = 1 WHERE departmentId = ? AND isDelete = 0";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, departmentId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void modifyWarehouse(String warehouseId, String warehouseType, String warehouseName, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    JSONObject warehouseJson = getSqlInfo("Warehouse_Table", "warehouseId", warehouseId, 12);
    if (warehouseJson.getInt("code") != 200) {
      console.err("未查询到修改仓库");
      resultJson.put("code", code.ErrorParam.value());
      resultJson.put("msg", code.ErrorParam.msg());
      handler.onData(resultJson);
      return;
    }

    if (!warehouseJson.getString("warehouseName").equals(warehouseName)) {
      if (!checkWarehouseNameRepetition(warehouseName)) {
        console.err("仓库名重复!");
        resultJson.put("code", code.ErrorWarehouseRepetition.value());
        resultJson.put("msg", code.ErrorWarehouseRepetition.msg());
        handler.onData(resultJson);
        return;
      }
    }

    String sql = "UPDATE Warehouse_Table SET warehouseType = ?,warehouseName = ? WHERE warehouseId = ? AND isDelete = 0";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, warehouseType, 12);
    sqlM.put(2, warehouseName, 12);
    sqlM.put(3, warehouseId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void inWarehouseItem(String itemName, String warehouseId, String itemType, int itemCount, float itemPrice, String supplierId, String itemBrokerage, String itemPayType, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    if (!checkItemNameRepetition(itemName, warehouseId)) {
      resultJson.put("code", code.ErrorItemNameRepetition.value());
      resultJson.put("msg", code.ErrorItemNameRepetition.msg());
      handler.onData(resultJson);
      return;
    }

    JSONObject warehouseJson = getSqlInfo("Warehouse_Table", "warehouseId", warehouseId, 12);

    if (warehouseJson.getInt("code") != 200) {
      resultJson.put("code", code.ErrorInWarehouseGet.value());
      resultJson.put("msg", code.ErrorInWarehouseGet.msg());
      handler.onData(resultJson);
      return;
    }

    JSONObject supplierJson = getSqlInfo("Supplier_Table", "supplierId", supplierId, 12);
    if (supplierJson.getInt("code") != 200) {
      resultJson.put("code", code.ErrorInWarehouseGetSupplier.value());
      resultJson.put("msg", code.ErrorInWarehouseGetSupplier.msg());
      handler.onData(resultJson);
      return;
    }

    String sql = "INSERT INTO Item_Table(itemId,InWarehouseId,itemInWarehouseCode,itemName,itemType,supplierId,supplierName,itemBrokerage,itemCount,itemPrice,itemBalance,itemPayType,createTime) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,now())";
    String uid = UUID.randomUUID().toString();
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, uid, 12);
    sqlM.put(2, warehouseId, 12);
    sqlM.put(3, warehouseJson.getString("warehouseCode"), 12);
    sqlM.put(4, itemName, 12);
    sqlM.put(5, itemType, 12);
    sqlM.put(6, supplierId, 12);
    sqlM.put(7, supplierJson.getString("supplierName"), 12);
    sqlM.put(8, itemBrokerage, 12);
    sqlM.put(9, itemCount, 4);
    sqlM.put(10, itemPrice, 3);
    float itemBalance = itemPrice * itemCount;
    sqlM.put(11, itemBalance, 3);
    console.log(itemBalance);
    sqlM.put(12, itemPayType, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void getDepartment(OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM Department_Table WHERE isDelete = 0";
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "departmentList", code.GetDepartmentNULL);
    JSONArray departmentList = resultJson.getJSONArray("departmentList");
    if (resultJson.getInt("code") != 200) {
      handler.onData(resultJson);
      return;
    }
    JSONArray arr = new JSONArray();
    for (Object obj : departmentList) {
      JSONObject departmentJson = JSONObject.fromObject(obj);
      if (!departmentJson.containsKey("departmentPrincipalId")) {
        arr.add(departmentJson);
        continue;
      }
      JSONObject userJson = getSqlInfo("User_Table", "userId", departmentJson.getString("departmentPrincipalId"), 12);
      if (userJson.getInt("code") == 200) {
        departmentJson.remove("departmentPrincipalId");
        departmentJson.put("departmentPrincipalName", userJson.getString("nickName"));
      }
      arr.add(departmentJson);
    }
    resultJson.put("departmentList", arr);
    handler.onData(resultJson);
  }

  public void selectWarehouseName(String warehouseName, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM Warehouse_Table WHERE isDelete = 0 AND warehouseName like ?";
    sqlM.put(1, "%" + warehouseName + "%", 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "departmentList", code.GetWarehouseNULL);
    handler.onData(resultJson);
  }

  public void selectSupplierName(String supplierName, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM Supplier_Table WHERE isDelete = 0 AND supplierName like ?";
    sqlM.put(1, "%" + supplierName + "%", 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "supplierList", code.GetSupplierNULL);
    handler.onData(resultJson);
  }

  public void selectItemName(String itemName, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM Item_Table WHERE isDelete = 0 AND itemName like ?";
    sqlM.put(1, "%" + itemName + "%", 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "itemList", code.GetItemNULL);
    handler.onData(resultJson);
  }

  public void selectDepartmentName(String departmentName, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM Department_Table WHERE departmentName like ?";
    sqlM.put(1, "%" + departmentName + "%", 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "departmentList", code.GetDepartmentNULL);
    handler.onData(resultJson);
  }

  public void getUserByDepartmentName(String departmentName, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM Department_Table WHERE departmentName = ?";
    sqlM.put(1, departmentName, 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), code.GetDepartmentNULL);
    if (resultJson.getInt("code") != 200) {
      handler.onData(resultJson);
      return;
    }
    sql = "SELECT * FROM User_Table WHERE departmentId = ?";
    sqlM = new sqlMap();
    sqlM.put(1, resultJson.getString("departmentId"), 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "userList", code.GetUserNULL);
    handler.onData(resultJson);
  }

  public void getDepartmentById(String departmentId, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM Department_Table WHERE isDelete = 0 AND departmentId = ?";
    sqlM.put(1, departmentId, 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), code.GetDepartmentNULL);
    if (resultJson.getInt("code") != 200) {
      handler.onData(resultJson);
      return;
    }
    if (resultJson.containsKey("departmentPrincipalId")) {
      JSONObject userJson = getSqlInfo("User_Table", "userId", resultJson.getString("departmentPrincipalId"), 12);
      resultJson.put("departmentPrincipalName", userJson.getString("nickName"));
      resultJson.remove("departmentPrincipalId");
    }
    handler.onData(resultJson);
  }

  public void getItem(int warehouseType, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    if (warehouseType > 9998) {
      sql = "SELECT * FROM Item_Table WHERE isDelete = 0";
    } else {
      sql = "SELECT * FROM Item_Table WHERE isDelete = 0 AND itemType = ?";
      sqlM.put(1, warehouseType, 4);
    }

    resultJson = listHelperQuery(executeQuery(sql, sqlM), "itemList", code.GetItemNULL);
    JSONArray itemList = resultJson.getJSONArray("itemList");
    if (resultJson.getInt("code") != 200) {
      handler.onData(resultJson);
      return;
    }
    JSONArray arr = new JSONArray();
    for (Object obj : itemList) {
      JSONObject itemJson = JSONObject.fromObject(obj);
      if (!itemJson.containsKey("InWarehouseId")) {
        arr.add(itemJson);
        continue;
      }
      JSONObject userJson = getSqlInfo("Warehouse_Table", "warehouseId", itemJson.getString("InWarehouseId"), 12);
      if (userJson.getInt("code") == 200) {
        itemJson.remove("InWarehouseId");
        itemJson.put("warehouseName", userJson.getString("warehouseName"));
      }
      arr.add(itemJson);
    }
    resultJson.put("itemList", arr);
    handler.onData(resultJson);
  }

  public void outWarehouse(String departmentTargetId, String outItemId, int outItemCount, String outItemBrokerage, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();

    JSONObject itemJson = getSqlInfo("Item_Table", "itemId", outItemId, 12);

    if (itemJson.getInt("code") != 200) {
      resultJson.put("code", code.GetOutItemNULL.value());
      resultJson.put("msg", code.GetOutItemNULL.msg());
      handler.onData(resultJson);
      return;
    }

    JSONObject departmentJson = getSqlInfo("Department_Table", "departmentId", departmentTargetId, 12);
    if (departmentJson.getInt("code") != 200) {
      resultJson.put("code", code.GetOutDepartmentTargetNULL.value());
      resultJson.put("msg", code.GetOutDepartmentTargetNULL.msg());
      handler.onData(resultJson);
      return;
    }

    JSONObject outWarehouseJson = getSqlInfo("Warehouse_Table", "warehouseId", itemJson.getString("InWarehouseId"), 12);

    if (outWarehouseJson.getInt("code") != 200) {
      resultJson.put("code", code.GetOutWarehouseNULL.value());
      resultJson.put("msg", code.GetOutWarehouseNULL.msg());
      handler.onData(resultJson);
      return;
    }

    DeductionItemCount(outItemId, outItemCount, result -> {
      if (result.getInt("code") != 200) {
        handler.onData(result);
        return;
      }

      JSONObject items = new JSONObject();
      items.put("itemId", itemJson.getString("itemId"));
      items.put("itemName", itemJson.getString("itemName"));
      items.put("itemCount", outItemCount);

      JSONArray arr;
      if (departmentJson.containsKey("departmentItem")) {
        arr = departmentJson.getJSONArray("departmentItem");
        JSONArray arr2 = new JSONArray();
        for (Object obj : arr) {
          JSONObject departItem = JSONObject.fromObject(obj);
          if (departItem.getString("itemId").equals(itemJson.getString("itemId"))) {
            departItem.put("itemCount", departItem.getInt("itemCount") + outItemCount);
          }
          arr2.add(departItem);
        }
        arr = arr2;
      } else {
        arr = new JSONArray();
        arr.add(items);
      }

      sqlMap sqlM = new sqlMap();
      String sql = "UPDATE Department_Table SET departmentItem = ? WHERE departmentId = ?";
      sqlM.put(1, arr.toString(), 12);
      sqlM.put(2, departmentTargetId, 12);
      reInsertJson(handler, resultJson, sql, sqlM);
      insertHistory(itemJson, departmentJson, outWarehouseJson, outItemBrokerage, outItemCount);
    });
  }

  public void getOutWarehouseHistory(OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM OutWarehouseHistory_Table";
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "historyList", code.GetOutWarehouseHistoryNULL);
    handler.onData(resultJson);
  }

  public void selectOutWarehouseHistory(String outWarehouseName, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM OutWarehouseHistory_Table WHERE outWarehouseName like ?";
    sqlM.put(1, "%" + outWarehouseName + "%", 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "historyList", code.GetOutWarehouseHistoryNULL);
    handler.onData(resultJson);
  }

  public void addItemDisk(String diskItemRecordUserName, String diskItemRecordItemName, String diskItemRecordItemSpe, String diskItemRecordItemType, int diskItemItemCount, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    String sql = "INSERT INTO DiskItemRecord_Table(diskItemRecordId,diskItemRecordUserName,diskItemRecordItemName,diskItemRecordItemSpe,diskItemRecordItemType,diskItemItemCount,createTime) VALUES (?,?,?,?,?,?,now())";
    sqlMap sqlM = new sqlMap();
    String uid = UUID.randomUUID().toString();
    sqlM.put(1, uid, 12);
    sqlM.put(2, diskItemRecordUserName, 12);
    sqlM.put(3, diskItemRecordItemName, 12);
    sqlM.put(4, diskItemRecordItemSpe, 12);
    sqlM.put(5, diskItemRecordItemType, 12);
    sqlM.put(6, diskItemItemCount, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  public void getItemDisk(OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM DiskItemRecord_Table";
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "diskItemRecordList", code.GetDiskNULL);
    handler.onData(resultJson);
  }

  public void selectItemDisk(String diskItemRecordItemName, OnDataHandler handler) {
    JSONObject resultJson;
    String sql;
    sqlMap sqlM = new sqlMap();
    sql = "SELECT * FROM DiskItemRecord_Table WHERE diskItemRecordItemName like ?";
    sqlM.put(1, "%" + diskItemRecordItemName + "%", 12);
    resultJson = listHelperQuery(executeQuery(sql, sqlM), "diskItemRecordList", code.GetDiskNULL);
    handler.onData(resultJson);
  }

  /**
   * -------------------------------------------------------------private----------------------------------------------------------------------------------
   */

  private boolean checkAccountRepetition(String username) {
    String sql = "SELECT userId FROM User_Table WHERE userName = ?";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, username, 12);
    List<Map<String, Object>> list = executeQuery(sql, sqlM);
    if (list.size() == 0) {
      console.log("账号不重复,おめでとう!");
      return true;
    }
    return false;
  }

  private boolean checkDepartmentNameRepetition(String departmentName) {
    String sql = "SELECT departmentId FROM Department_Table WHERE departmentName = ?";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, departmentName, 12);
    List<Map<String, Object>> list = executeQuery(sql, sqlM);
    if (list.size() == 0) {
      console.log("部门名不重复,おめでとう!");
      return false;
    }
    return true;
  }

  private boolean checkSupplierNameRepetition(String supplierName) {
    String sql = "SELECT supplierId FROM Supplier_Table WHERE supplierName = ? AND isDelete = 0";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, supplierName, 12);
    List<Map<String, Object>> list = executeQuery(sql, sqlM);
    if (list.size() == 0) {
      console.log("供应商名不重复,おめでとう!");
      return true;
    }
    return false;
  }

  private boolean checkWarehouseNameRepetition(String warehouseName) {
    String sql = "SELECT warehouseId FROM Warehouse_Table WHERE warehouseName = ? AND isDelete = 0";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, warehouseName, 12);
    List<Map<String, Object>> list = executeQuery(sql, sqlM);
    if (list.size() == 0) {
      console.log("仓库名不重复,おめでとう!");
      return true;
    }
    return false;
  }

  private boolean checkItemNameRepetition(String itemName, String warehouseId) {
    String sql = "SELECT itemId FROM Item_Table WHERE itemName = ? AND isDelete = 0";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, itemName, 12);
    List<Map<String, Object>> list = executeQuery(sql, sqlM);
    if (list.size() == 0) {
      console.log("物资名不重复,おめでとう!");
      return true;
    }
    return false;
  }

  private boolean checkUserOldPassword(String userId, String oldPassword) {
    String sql = "SELECT username FROM User_Table WHERE password = ? AND userId = ?";
    sqlMap sqlM = new sqlMap();
    sqlM.put(1, oldPassword, 12);
    sqlM.put(2, userId, 12);
    List<Map<String, Object>> list = executeQuery(sql, sqlM);
    if (list.size() == 0) {
      return false;
    }
    console.log("旧密码验证正确,おめでとう!");
    return true;
  }

  private synchronized void DeductionItemCount(String itemId, int deductedCount, OnDataHandler handler) {
    JSONObject resultJson = new JSONObject();
    JSONObject itemJson = getSqlInfo("Item_Table", "itemId", itemId, 12);

    if (itemJson.getInt("code") != 200) {
      resultJson.put("code", code.GetOutItemNULL.value());
      resultJson.put("msg", code.GetOutItemNULL.msg());
      handler.onData(resultJson);
      return;
    }

    int itemCount = itemJson.getInt("itemCount");

    if (itemCount < deductedCount) {
      resultJson.put("code", code.ItemCountNoEnough.value());
      resultJson.put("msg", code.ItemCountNoEnough.msg());
      handler.onData(resultJson);
      return;
    }

    itemCount -= deductedCount;

    sqlMap sqlM = new sqlMap();
    String sql = "UPDATE Item_Table SET itemCount = ? WHERE itemId = ?";
    sqlM.put(1, itemCount, 4);
    sqlM.put(2, itemId, 12);
    reInsertJson(handler, resultJson, sql, sqlM);
  }

  private void insertHistory(JSONObject itemJson, JSONObject departmentJson, JSONObject warehouseJson, String outItemBrokerage, int outItemCount) {
    String sql = "INSERT INTO OutWarehouseHistory_Table(outId,outWarehouseId,outWarehouseName,outDepartmentTargetId,outDepartmentTargetName,outItemName,outItemId,outItemCount,outItemBrokerage,createTime) VALUES (?,?,?,?,?,?,?,?,?,now())";
    sqlMap sqlM = new sqlMap();
    String uid = UUID.randomUUID().toString();
    sqlM.put(1, uid, 12);
    sqlM.put(2, warehouseJson.getString("warehouseId"), 12);
    sqlM.put(3, warehouseJson.getString("warehouseName"), 12);
    sqlM.put(4, departmentJson.getString("departmentId"), 12);
    sqlM.put(5, departmentJson.getString("departmentName"), 12);
    sqlM.put(6, itemJson.getString("itemName"), 12);
    sqlM.put(7, itemJson.getString("itemId"), 12);
    sqlM.put(8, outItemCount, 4);
    sqlM.put(9, outItemBrokerage, 12);
    executeUpdate(sql, sqlM);
  }
}
